/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cinvestav.adviseme.util;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;

import cinvestav.adviseme.databasemodel.IPersonaDB;
import cinvestav.adviseme.databasemodel.PersonaDB;
import cinvestav.adviseme.datamodel.Persona;

/**
 * 
 * @author javier
 */
public class UserDetailsServiceImpl implements UserDetailsService {

	private IPersonaDB userDao;

	public UserDetailsServiceImpl() {
		try {
			this.userDao = new PersonaDB();
		} catch (DBException ex) {
			Logger.getLogger(UserDetailsServiceImpl.class.getName()).log(
					Level.SEVERE, null, ex);
		}
	}

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		try {
			Persona user = (Persona) userDao.getByUserName(username);
			if (user != null && user.getId() != null && user.getId() != 0) {
				Logger.getLogger(UserDetailsServiceImpl.class.getName()).log(
						Level.SEVERE, null, "AQUI");
				return makeUser(user);
			}else{
				throw new UsernameNotFoundException("User not found: " + username);
			}
		} catch (DBException ex) {
			throw new UsernameNotFoundException(ex.getMessage());
		}
	}

	private org.springframework.security.userdetails.User makeUser(Persona user) {
		return new org.springframework.security.userdetails.User(user.getNombreUsuario()+"@"+user.getId(),
				user.getPassword(), true, true, true, true, makeGrantedAuthorities(user));
	}

	private GrantedAuthority[] makeGrantedAuthorities(Persona user) {
		GrantedAuthority[] result = new GrantedAuthority[1];
		int i = 0;
		// if(user.getTipoUsuario() == 1){
		result[i++] = new GrantedAuthorityImpl("ROLE_ALLACCESS");
		// }else{
		// result[i++] = new GrantedAuthorityImpl("ROLE_URLACCESS");
		// }
		return result;
	}

}
